package com.test;

import java.net.Socket;

import com.test.SocketService.SocketBinder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AndroidSocketConnect extends Activity{
    
	final private String TAG = "SocketConnect";
	private SocketBinder mBinder;
	private SocketPreview socPreview;
	private Conn conn;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button close = (Button) findViewById(R.id.close);
        close.setOnClickListener(new OnClickListener() {			
        	public void onClick(View v) {				
        		toast("Goodbye");
            	finish();
        	}		
        });	
    }
    
    public void onResume(){
    	super.onResume();
		
    	Intent service = new Intent(this, SocketService.class);
        
        conn = new Conn(this);
        Log.v(TAG, "AndroidSocketConnect attempting to bind to service");
        this.bindService(service, conn, Context.BIND_AUTO_CREATE);
        
    }
    
    public void onPause(){
    	super.onPause();
    	close();
    }
    public void close(){
    	conn.close();
    }
    
    class Conn implements ServiceConnection{
    	private AndroidSocketConnect mContext;
    	private Socket socket;
    	
    	Conn(AndroidSocketConnect mContext){
    		this.mContext = mContext;
    	}
		@Override
		public void onServiceConnected(ComponentName arg0, IBinder socketBinder) {
			Log.v(TAG, "AndroidSocketConnect bound");
			mBinder = (SocketBinder)socketBinder;
			
	        try {
	        Log.v(TAG, "AndroidSocketConnect getting socket");
	        socket = mBinder.getService().getSocket();
	        
	        socPreview = new SocketPreview(mContext, socket);
			
	        }
	        catch (Exception e){
	        	Log.v(TAG, "AndroidSocketConnect EXCEPTION E!");
	        	Log.v(TAG, "AndroidSocketConnect EXCEPTION E!");
	        	Log.v(TAG, "AndroidSocketConnect EXCEPTION E!");
	        	Log.v(TAG, "AndroidSocketConnect EXCEPTION E!");
	        	e.printStackTrace();
				mContext.unbindService(this);
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			System.out.println("AndroidSocketConnect unbound");
			close();
		}
		
		public void close(){
			socPreview.close();
			mContext.unbindService(this);
		}
    }

    private void toast(String messageText) {
		Toast toast = Toast.makeText(
        		this,
        		messageText,
                Toast.LENGTH_LONG
        );
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
}